import spawn from 'cross-spawn';
import path from 'path';

const whistleSpawn = path.join(
  __dirname,
  '../node_modules/whistle/bin/whistle.js',
);
export function proxy({ type, shadowRules, port = '8899' }: any) {
  if (!['start', 'run', 'stop', 'restart', 'off', 'init'].includes(type)) {
    console.log(`命令不存在`);
    spawn.sync('qps', ['proxy', '--help'], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    return;
  }

  if (type === 'init') {
    spawn.sync('node', [whistleSpawn, 'start', '--init'], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    spawn.sync('node', [whistleSpawn, 'proxy', port], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    return;
  }
  if (type === 'off') {
    spawn.sync('node', [whistleSpawn, 'proxy', type], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    spawn.sync('node', [whistleSpawn, type], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    return;
  }

  if (type === 'stop') {
    spawn.sync('node', [whistleSpawn, type], {
      cwd: process.cwd(),
      stdio: 'inherit',
    });
    return;
  }

  spawn.sync('node', [whistleSpawn, type, '-r', shadowRules, '-p', port], {
    cwd: process.cwd(),
    stdio: 'inherit',
  });
}
